package com.taotao.sso.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.pojo.CommonResult;
import com.taotao.common.utils.CookieUtils;
import com.taotao.sso.pojo.User;
import com.taotao.sso.service.UserService;

@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserService userService;

	@GetMapping("register")
	public String toRegister() {

		return "register";
	}

	/**
	 * 校验用户信息是否可用
	 * 
	 * @param param
	 * @param type
	 * @return
	 */
	@GetMapping("/check/{param}/{type}")
	public ResponseEntity<Boolean> checkUser(@PathVariable("param") String param, @PathVariable("type") Integer type) {

		try {
			Boolean b = this.userService.checkUser(param, type);
			if (b == null) {
				return ResponseEntity.badRequest().build();
			}
			// 不管是否可用都应返回200
			return ResponseEntity.ok(b);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}

	/**
	 * 用户注册
	 * 
	 * @param user
	 * @return
	 */
	@PostMapping
	@ResponseBody
	public CommonResult register(@Valid User user, BindingResult result) {

		// 数据校验
		if (result.hasErrors()) {
			// 搜集所有的错误信息
			List<String> msgs = new ArrayList<>();
			// 获取所有错误对象
			List<ObjectError> errors = result.getAllErrors();
			// 遍历错误对象
			for (ObjectError error : errors) {
				msgs.add(error.getDefaultMessage());
			}
			// 响应错误信息
			return CommonResult.build(400, StringUtils.join(msgs, ","));
		}

		try {

			Boolean b = this.userService.register(user);
			if (b) {
				return CommonResult.ok();
			}
			return CommonResult.build(400, "参数不合法！");
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResult.build(500, e.getMessage());
		}
	}

	@GetMapping("login")
	public String toLogin() {

		return "login";
	}

	/**
	 * 实现的登陆
	 * @param userName
	 * @param password
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping("doLogin")
	@ResponseBody
	public CommonResult doLogin(@RequestParam("username") String userName, @RequestParam("password") String password,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			// 开始登陆
			String token = this.userService.login(userName, password);
			// 登陆成功
			if(StringUtils.isNotBlank(token)){
				// 设置cookie
				CookieUtils.setCookie(request, response, "TT_TOKEN", token, 3600*3);
				return CommonResult.ok(token);
			}
			return CommonResult.build(400, "登陆失败！");
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResult.build(500, e.getMessage());
		}
	}
	
	/**
	 * 根据token查询用户信息
	 * @param token
	 * @return
	 */
	@GetMapping("query/{token}")
	public ResponseEntity<User> queryUserByToken(@PathVariable("token")String token){
		
		try {
			User user = this.userService.queryUserByToken(token);
			if(user == null){
				return ResponseEntity.notFound().build();
			}
			return ResponseEntity.ok(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}

}
